﻿using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;

namespace Soul.IdentityServer.Hosting
{
    internal class IdentityServerMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly IEnumerable<EndpointDescriptor> _endpoints;

        public IdentityServerMiddleware(RequestDelegate next, IEnumerable<EndpointDescriptor> endpoints)
        {
            _next = next;
            _endpoints = endpoints;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            if (!context.Request.Path.HasValue)
            {
                await _next(context);
                return;
            }
            var endpoint = FindEndpoint(context);
            if (endpoint == null)
            {
                await _next(context);
                return;
            }
            try
            {
                var result = await endpoint.HandleAsync(context);
                await result.ExecuteAsync(context);
            }
            catch (ValidationException validationException)
            {
                await new BadRequestEndpointResult(validationException.Error, validationException.ErrorDescription).ExecuteAsync(context);
            }
          
        }


        private EndpointBase? FindEndpoint(HttpContext context)
        {
            var descriptor = _endpoints
                .Where(a => a.Path.Equals(context.Request.Path.Value, StringComparison.OrdinalIgnoreCase))
                .FirstOrDefault();
            
            if (descriptor == null)
                return default;

            return context.RequestServices.GetRequiredService(descriptor.Type) as EndpointBase;
        }
    }
}
